import { MciInput, MciSelect, MciOption } from '@/components/base';
import { ElForm, ElFormItem } from 'element-plus';
import { getFlowResultLatestExecParams } from '@/api/decision-engine';
import type { IGetFlowResultLatestExecParamsRes } from '@/api/decision-engine';
export const SingleTest = defineComponent({
  props: {
    formFields: {
      type: Array,
      default: () => []
    },
    flowVars: {
      type: Array,
      default: () => []
    },
    flowId: {
      type: String,
      default: ''
    }
  },
  setup(props, context) {
    const formRef = ref<any>(null);
    const paramsVars = ref<Record<string, any>>({});
    const latestList = ref<any>([]);
    const latestParamsIndex = ref<number>(null);

    const initData = async () => {
      const data: IGetFlowResultLatestExecParamsRes = await getFlowResultLatestExecParams({ flowId: props.flowId });
      if (data && data.length > 0) {
        latestList.value = data.map((item, index) => {
          return {
            id: index + 1,
            detail: JSON.stringify(item)
          };
        });
      } else {
        latestList.value = [];
      }
    };

    const validate = () => {
      return new Promise((resolve, reject) => {
        formRef.value?.validate((valid: boolean) => {
          if (valid) {
            resolve(paramsVars.value);
          } else {
            console.error('表单校验失败');
            reject(new Error('表单校验失败'));
          }
        });
      });
    };

    watch(
      () => props.flowVars,
      (val) => {
        if (val) {
          paramsVars.value = JSON.parse(JSON.stringify(props.flowVars));
        }
      }
    );

    watch(
      () => latestParamsIndex.value,
      (val) => {
        if (val) {
          paramsVars.value = JSON.parse(latestList.value[val - 1]?.detail);
        } else {
          paramsVars.value = JSON.parse(JSON.stringify(props.flowVars));
        }
      }, { deep: true }
    );

    initData();

    context.expose({ validate });

    return () => {
      return (
        <>
          <div class="singleTest-select">
            <h3>最近10次执行参数</h3>
            <MciSelect v-model={latestParamsIndex.value} placeholder="请选择执行记录" class="w-full mt-16 mb-16" clearable>
              {latestList.value?.map((item) => {
                return <MciOption label={item.detail} value={item.id} />;
              })}
            </MciSelect>
          </div>
          <ElForm ref={formRef} model={paramsVars.value} labelPosition="top">
            {props.formFields.map((field) => (
              <ElFormItem
                label={field.label}
                prop={field.name}
                rules={[
                  {
                    required: true,
                    message: `请输入${field.label}`,
                    trigger: ['change', 'blur']
                  }
                ]}>
                <MciInput v-model={paramsVars.value[field.name]} placeholder={`请输入${field.label}`} />
              </ElFormItem>
            ))}
            <ElFormItem label="隐藏" style="display: none;" prop="hidden">
              <MciInput />
            </ElFormItem>
          </ElForm>
        </>
      );
    };
  }
});
